package com.ccc.excel.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ccc.excel.controller.ExcelTransController;
import com.ccc.excel.pojo.AssetUpdateData;
import com.ccc.excel.pojo.AssetImportData;
import com.ccc.excel.service.ExcelTransService;
import com.ccc.excel.util.MyExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;

/**
 * @author superC
 * @version 2.0.0
 * @date 2023/11/7
 */

@Service
public class ExcelTransServiceImpl implements ExcelTransService {
    protected static final Logger logger = LoggerFactory.getLogger(ExcelTransServiceImpl.class);

    @Override
    public void toTrans(MultipartFile[] file, HttpServletResponse response) throws Exception {
        // 先取第一个文件，为需要调整数据的文件
        MultipartFile isUptFile = file[0];
        // 获取文件中的数据
        List<AssetImportData> allAssetList = MyExcelUtils.importExcel(isUptFile, AssetImportData.class);
        logger.info("获取到需要调整数据的资产数为{}", allAssetList.size());

        // 第二个文件，为需要对比的数据
        MultipartFile contrastFile = file[1];
        List<AssetUpdateData> categoryList = MyExcelUtils.importExcel(contrastFile, AssetUpdateData.class);
        logger.info("获取到需要对比的资产数为{}", categoryList.size());

        logger.info("读取完毕，开始整合...");
        long start = System.currentTimeMillis();
        for (AssetImportData data : allAssetList) {
            // 遍历内部循环
            Iterator<AssetUpdateData> it = categoryList.iterator();
            while (it.hasNext()) {
                AssetUpdateData uptData = it.next();
                // 如果资产编码相同
                if (StrUtil.equals(data.getAssetCode(), uptData.getAssetCode())) {
                    // 赋值资产类别
                    data.setCategory(uptData.getCategory());
                    if (StrUtil.isBlank(data.getMdepart())) {
                        data.setMdepart(uptData.getMdepart());
                    }
                    if (StrUtil.isBlank(data.getUsingLocation())) {
                        data.setUsingLocation(uptData.getUsingLocation());
                    }
                    // 删除内部遍历元素
                    it.remove();
                    // 跳出内部循环
                    break;
                }
            }
        }
        long end = System.currentTimeMillis();
        logger.info("整合完毕，整合耗时：" + (end - start) + "毫秒");
        logger.info("准备导出...");
        // 将整合后的文件再导出Excel
        long start2 = System.currentTimeMillis();
        MyExcelUtils.exportExcel(allAssetList, AssetImportData.class, "资产列表", "资产", "10月整合后的资产数据", response);
        long end2 = System.currentTimeMillis();
        logger.info("已导出，导出耗时：" + (end2 - start2) + "毫秒");
    }
}
